package org.example.xx2.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeService {
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    private static final String CODE_PREFIX = "verification_code:";
    private static final int CODE_LENGTH = 6;
    private static final long CODE_EXPIRE_TIME = 5; // 5分钟
    
    public String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
    
    public void saveCode(String key, String code) {
        redisTemplate.opsForValue().set(CODE_PREFIX + key, code, CODE_EXPIRE_TIME, TimeUnit.MINUTES);
    }
    
    public String getCode(String key) {
        return redisTemplate.opsForValue().get(CODE_PREFIX + key);
    }
    
    public boolean verifyCode(String key, String code) {
        String savedCode = getCode(key);
        if (savedCode != null && savedCode.equals(code)) {
            // 验证成功后删除验证码
            redisTemplate.delete(CODE_PREFIX + key);
            return true;
        }
        return false;
    }
    
    public void deleteCode(String key) {
        redisTemplate.delete(CODE_PREFIX + key);
    }
} 